<?php
// 本类由系统自动生成，仅供测试用途
namespace Api\Controller;

use Think\Controller;

class OrderController extends PublicController
{

    /**
     * 购买订单列表
     * @author tiedong
     * @date 2018-01-18
     */
    public function index()
    {
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }

        //分页
        $per_page = !empty($_GET['per_page']) ? intval($_GET['per_page']) : 10;//每页显示十条
        $page = $_GET['page'] ? ($_GET['page'] - 1) * $per_page : 0;//页数
        $limit = "$page,$per_page";
        $orders = M("order");
        $orderp = M("order_product");
        //按条件查询
        $condition = array();
        $condition['del'] = 0;
        $condition['back'] = '0';
        $condition['uid'] = intval($uid);
        //$condition['status'] = 10;
        $order_type = trim($_GET['order_type']);
        if ($order_type) {
            switch ($order_type) {
                case '10':
                    $condition['status'] = 10;
                    break;
                case '20':
                    $condition['status'] = 20;
                    break;
                case '30':
                    $condition['status'] = 30;
                    break;
                case '40':
                    $condition['status'] = 40;
                    break;
                case '50':
                    $condition['status'] = 50;
                    break;
                default:
                    $condition['status'] = 10;
                    break;
            }
        }

        //获取总页数
        $count = $orders->where($condition)->count();
        $order_status = array('0' => '已取消', '10' => '待付款', '20' => '已付款', '30' => '待发货', '40' => '已发货', '50' => '交易完成', '51' => '交易关闭', '52' => '申请退款', '53' => '拒绝退款', '54' => '退款成功');

        $order = $orders->where($condition)->order('id desc')->field('id,order_sn,shop_id,amount,bi_id,vid,pay_sn,status,price,is_dui,type,product_num,photo_x,post,kuaidi_num')->limit($limit)->select();
        foreach ($order as $n => $v) {
            $order[$n]['name'] = M("brand")->where("id=" . $v['shop_id'])->getField("name");
            $order[$n]['brand_photo'] = __DATAURL__ . "UploadFiles/" . M("brand_image")->where("id=" . $v['vid'])->getField("brand_photo");
            $order[$n]['desc'] = $order_status[$v['status']];
            $prolist = $orderp->where('order_id=' . intval($v['id']))->select();
            foreach ($prolist as $k => $value) {
                $prolist[$k]['photo_x'] = __DATAURL__ . $value['photo_x'];
            }
            $order[$n]['order_product'] = $prolist;
        }
        $returnArr = array(
            'ord'        => $order,
            'count'      => $count,
            'page'       => intval($page) + 1,
            'per_page'   => intval($per_page),
            'total_page' => intval(ceil($count / 10)),
        );
        $this->json_result($returnArr);
        exit();

    }

    //***************************
    //  用户获取订单信息接口
    //***************************
    public function get_more()
    {
        $uid = intval($_REQUEST['uid']);
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }

        //分页
        $pages = intval($_REQUEST['page']);
        if (!$pages) {
            $pages = 2;
        }
        $limit = $pages * 7 - 7;

        $orders = M("order");
        $orderp = M("order_product");
        $shangchang = M('shangchang');

        //按条件查询
        $condition = array();
        $condition['del'] = 0;
        $condition['back'] = '0';
        $condition['uid'] = intval($uid);
        $condition['status'] = 10;
        $order_type = trim($_REQUEST['order_type']);
        if ($order_type) {
            switch ($order_type) {
                case 'pay':
                    $condition['status'] = 10;
                    break;
                case 'deliver':
                    $condition['status'] = 20;
                    break;
                case 'receive':
                    $condition['status'] = 30;
                    break;
                case 'evaluate':
                    $condition['status'] = 40;
                    break;
                case 'finish':
                    $condition['status'] = array('IN', array(40, 50));
                    break;
                default:
                    $condition['status'] = 10;
                    break;
            }
        }

        //获取总页数
        $count = $orders->where($condition)->count();
        $eachpage = 7;

        $order_status = array('0' => '已取消', '10' => '待付款', '20' => '已付款', '30' => '待发货', '40' => '已发货', '50' => '交易完成', '51' => '交易关闭');

        $order = $orders->where($condition)->order('id desc')->field('id,order_sn,pay_sn,status,price,type,product_num')->limit($limit . ',7')->select();
        foreach ($order as $n => $v) {
            $order[$n]['desc'] = $order_status[$v['status']];
            $prolist = $orderp->where('order_id=' . intval($v['id']))->find();
            $order[$n]['photo_x'] = __DATAURL__ . $prolist['photo_x'];
            $order[$n]['pid'] = $prolist['pid'];
            $order[$n]['name'] = $prolist['name'];
            $order[$n]['price_yh'] = $prolist['price'];
            $order[$n]['pro_count'] = $orderp->where('order_id=' . intval($v['id']))->getField('COUNT(id)');
        }

        echo json_encode(array('status' => 1, 'ord' => $order));
        exit();

    }

    //***************************
    //  用户退款退货接口
    //***************************
    public function order_refund()
    {
        $uid = intval($_REQUEST['uid']);
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }

        //分页
        $pages = intval($_REQUEST['page']);
        if (!$pages) {
            $pages = 0;
        }

        $orders = M("order");
        $orderp = M("order_product");
        $shangchang = M('shangchang');

        $condition = array();
        $condition['back'] = array('gt', '0');
        //获取总页数
        $count = $orders->where($condition)->count();
        $the_page = ceil($count / 6);

        $refund_status = array('1' => '退款申请中', '2' => '已退款', '3' => '处理中', '4' => '已拒绝');

        $order = $orders->where($condition)->order('back_addtime desc')->field('id,price,order_sn,product_num,back,back_addtime')->limit($pages . ',6')->select();
        foreach ($order as $n => $v) {
            $order[$n]['desc'] = $refund_status[$v['back']];
            $prolist = $orderp->where('order_id=' . intval($v['id']))->find();
            $order[$n]['photo_x'] = __DATAURL__ . $prolist['photo_x'];
            $order[$n]['pid'] = $prolist['pid'];
            $order[$n]['name'] = $prolist['name'];
            $order[$n]['price_yh'] = $prolist['price'];
            $order[$n]['back_addtime'] = date("Y-m-d H:i", $v['back_addtime']);
            $order[$n]['pro_count'] = $orderp->where('order_id=' . intval($v['id']))->getField('COUNT(id)');
        }

        echo json_encode(array('status' => 1, 'ord' => $order));
        exit();
    }

    //***************************
    //  用户退款退货接口
    //***************************
    public function get_refund_more()
    {
        $uid = intval($_REQUEST['uid']);
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }

        //分页
        $pages = intval($_REQUEST['page']);
        if (!$pages) {
            $pages = 2;
        }
        $limit = $pages * 6 - 6;

        $orders = M("order");
        $orderp = M("order_product");
        $shangchang = M('shangchang');

        $condition = array();
        $condition['back'] = array('gt', '0');
        //获取总页数
        $count = $orders->where($condition)->count();
        $the_page = ceil($count / 6);

        $refund_status = array('1' => '退款申请中', '2' => '已退款', '3' => '处理中', '4' => '已拒绝');

        $order = $orders->where($condition)->order('back_addtime desc')->field('id,price,order_sn,product_num,back,back_addtime')->limit($limit . ',6')->select();
        foreach ($order as $n => $v) {
            $order[$n]['desc'] = $refund_status[$v['back']];
            $prolist = $orderp->where('order_id=' . intval($v['id']))->find();
            $order[$n]['photo_x'] = __DATAURL__ . $prolist['photo_x'];
            $order[$n]['pid'] = $prolist['pid'];
            $order[$n]['name'] = $prolist['name'];
            $order[$n]['price_yh'] = $prolist['price'];
            $order[$n]['back_addtime'] = date("Y-m-d H:i", $v['back_addtime']);
            $order[$n]['pro_count'] = $orderp->where('order_id=' . intval($v['id']))->getField('COUNT(id)');
        }

        echo json_encode(array('status' => 1, 'ord' => $order));
        exit();
    }


    //***************************
    //  用户订单编辑接口
    //***************************
    public function orders_edit()
    {

        $orders = M("order");
        $order_id = intval($_REQUEST['id']);
        $type = $_REQUEST['type'];

        $check_id = $orders->where('id=' . intval($order_id) . ' AND del=0')->getField('id');
        if (!$check_id || !$type) {
            echo json_encode(array('status' => 0, 'err' => '订单信息错误.' . __LINE__));
            exit();
        }

        $data = array();
        if ($type === 'cancel') {
            $data['status'] = 0;
        } elseif ($type === 'receive') {
            $data['status'] = 40;
        } elseif ($type === 'refund') {
            $data['back'] = 1;
            $data['back_remark'] = $_REQUEST['back_remark'];
        }

        if ($data) {
            $result = $orders->where('id=' . intval($order_id))->save($data);
            if ($result !== false) {
                echo json_encode(array('status' => 1));
                exit();
            } else {
                echo json_encode(array('status' => 0, 'err' => '操作失败.' . __LINE__));
                exit();
            }
        } else {
            echo json_encode(array('status' => 0, 'err' => '订单信息错误.' . __LINE__));
            exit();
        }
    }

    /**
     * 订单详情
     * @author tiedong
     * @date 2018-01-24
     */
    public function order_details()
    {
        include_once __DOCUMENT__ . "/extend/kuaidi/kuaidi100.php";
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }
        $order_id = intval($_GET['order_id']);
        $orders = M("order");
        $orderp = M("order_product");
        $order_info = $orders->where('id=' . intval($order_id . ' AND del=0'))
            ->field('id,order_sn,shop_id,status,addtime,vid,price,type,tel,receiver,address_xq,product_num,amount,price_h,post,kuaidi_num,back')->find();
        if (!$order_info) {
            echo json_encode(array('status' => 0, 'err' => '订单信息错误.'));
            exit();
        }
        $order_info['photo_image'] = __DATAURL__ . "UploadFiles/" . M("brand_image")->where('id=' . $order_info['vid'])->getField("brand_photo");
        $order_info['name'] = M("brand")->where("id=" . $order_info['shop_id'])->getField("name");
        $order_status = array('0' => '已取消', '10' => '待付款', '20' => '已付款', '30' => '待发货', '40' => '已发货', '50' => '交易完成', '51' => '交易关闭', '52' => '申请退款', '53' => '拒绝退款', '54' => '退款成功');
        $pay_type = array('cash' => '现金支付', 'alipay' => '支付宝', 'weixin' => '微信支付');
        $order_info['order_status'] = $order_status[$order_info['status']];
        //$order_info['pay_type'] = $pay_type[$order_info['type']];
        $order_info['addtime'] = date('Y-m-d H:i:s', $order_info['addtime']);
        $order_info['product'] = $orderp->where('order_id=' . intval($order_info['id']))->field("name,price,num")->select();

        //获取最新物流信息
        $mm = $order_info['kuaidi_num'];
        $code = $order_info['post'];
        $ff = new \Kuaidi100();
        $data = $ff->kuaiDiInfo($code, $mm);

        // 售后的信息
        $back = [];
        $backFirst = M("return_order")->where('order_id=' . $order_info['id'])->order('id desc')->find();
        if ($backFirst) {
            $back = $backFirst;
        }
        $back['back_times'] = M("return_order")->where('order_id=' . $order_info['id'])->count('id');

        $returnArr = array(
            'wuliu'      => $data['data'][0],
            'order_info' => $order_info,
            'back'       => $back
        );
        $this->json_result($returnArr);
        exit();
    }

    //***************************
    //  用户订单评论接口
    //***************************
    public function order_comment()
    {
        $id = explode(',', $_GET['id']);

        $orderid = (int)$_GET['orderid'];
        $order_product = M('order_product');
        $order = M('order');
        $orderr = $order->where('id=' . $orderid)->select();
        foreach ($id as $key => $value) {
            $result[$key] = $order_product->where('`order`=' . $orderid . ' and pid=' . $value)->select();
        }
        $this->assign('result', $result);
        $this->assign('orderr', $orderr);
        $this->display();
    }

    //***************************
    //  用户订单评论接口
    //***************************
    public function addMessage()
    {
        $product_dp = M('product_dp');
        $order_product = M("order_product");
        $order = M("order");
        //获取商品的ID
        $id = $_POST['pid'];
        $id = explode(",", $id);
        $data['orderid'] = $_POST['orderid'];
        $data['type'] = 1;
        $status['mstatus'] = 1;
        $data['uid'] = $_SESSION['ID'];
        $data['addtime'] = time();
        foreach ($id as $key => $value) {
            $data['pid'] = $value;
            $data['concent'] = $_POST['content' . $data['pid']];
            $data['num'] = $_POST['pingfen' . $data['pid']];
            $result = $product_dp->add($data);
        }
        /*$meresult = $product_dp->where('uid='.$_SESSION['ID'].' and orderid='.$_POST['orderid'].' and pid='.$_POST['id'])->select();
        if($meresult){
        	echo 2;
        	exit();
        }*/

        if ($result) {
            $order->where('id=' . $_POST['orderid'])->save($status);
            $this->success('评价成功', U('User/orders', array('key' => $_POST['key'])));
        } else {
            $this->error('评价失败');
        }

    }

    /**
     * 取消订单
     * @author tiedong
     * @date 2018-02-02
     */
    public function cancelOrder()
    {
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }
        $order_id = intval($_GET['order_id']);
        $result = M("order")->where("id=" . $order_id)->setField("status", 0);
        if ($result) {
            $jifen = M("order")->where("id=" . $order_id)->getField("price_h") * 100;
            M("user")->where("id=" . $uid)->setInc("jifen", intval($jifen));
            $this->json_result("取消成功！");
            exit;
        } else {
            $this->json_error("取消订单失败！");
            exit;
        }
    }

    /**
     * 签收订单
     * @author tiedong
     * @date 2018-02-02
     */
    public function confirmOrder()
    {
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }
        $order_id = intval($_GET['order_id']);
        $result = M("order")->where("id=" . $order_id)->setField("status", 50);
        if ($result) {
            $orderInfo = M("order")->where("id=" . $order_id)->find();
            $brandCanJiFen = M('brand')->where('id=' . $orderInfo['shop_id'])->getField('type');
            if ($orderInfo['type'] == "weixin" && $brandCanJiFen == 0 && $orderInfo['price_h'] == 0) {
                $jifen = $orderInfo['amount'];
                M("user")->where("id=" . $uid)->setInc("jifen", intval($jifen));
                $this->addJifen($uid, intval($jifen));
            }
            $this->json_result("取消成功！");
            exit;
        } else {
            $this->json_error("取消订单失败！");
            exit;
        }
    }

    public function addJifen($uid, $jifen)
    {
        $time = time();
        $sql = " INSERT INTO lr_user_sign (`uid`,`type`,`jifen`,`addtime`) VALUES ($uid,1,$jifen,$time)";
        M("user_sign")->execute($sql);
    }


    /**
     * 用户查看物流的消息
     * @author tiedong
     * @date 2018-02-06
     */
    public function checkWuliu()
    {
        include_once __DOCUMENT__ . "/extend/kuaidi/kuaidi100.php";
        $mm = !empty($_GET['nu']) ? $_GET['nu'] : null;
        $code = !empty($_GET['code']) ? $_GET['code'] : null;
        $ff = new \Kuaidi100();
        $data = $ff->kuaiDiInfo($code, $mm);
        if ($data['message'] == '参数错误') {
            $msg = "{$mm}--运单暂无结果";
            $ret = array(
                'code' => 0,
                'msg'  => $msg
            );
            $this->json_result($ret);
        } else {
            $data['name'] = $this->getKuaiNaem($code);
            $this->json_result($data);
        }
    }

    /**
     * 删除订单
     * @author tiedong
     * @date 2018-02-06
     */
    public function delOrder()
    {
        $uid = intval($this->get("id"));
        if (!$uid) {
            echo json_encode(array('status' => 0, 'err' => '登录状态异常'));
            exit();
        }
        $order_id = intval($_GET['order_id']);
        $result = M("order")->where("id=" . $order_id)->delete();
        if ($result) {
            $this->json_result("删除成功！");
            exit;
        } else {
            $this->json_error("删除失败！");
            exit;
        }
    }

    public function getKuaiNaem($code)
    {
        $wuliu = C("WULIU");
        foreach ($wuliu as $key => $value) {
            if ($key == $code) {
                $name = $value['0'];
                break;
            }
        }
        return $name;
    }


}